package com.jlnk.stockdemo.viewmodel;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jlnk.stockdemo.bean.BondsListRequest;
import com.jlnk.stockdemo.bean.BondsListResponse;
import com.jlnk.stockdemo.callback.ResponseCallback;
import com.jlnk.stockdemo.utils.NetworkUtils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

public class BondsViewModel extends ViewModel {
    private static final String TAG = "BondsViewModel";
    private MutableLiveData<List<BondsListResponse.Data.Bonds>> bondsListLiveData;

    public BondsViewModel() {
        bondsListLiveData = new MutableLiveData<>();
    }

    public LiveData<List<BondsListResponse.Data.Bonds>> getBondsListLiveData() {
        return bondsListLiveData;
    }

    // 获取债券列表
    public void fetchBondsList() {
        NetworkUtils.sendPostRequest(new BondsListRequest(), new ResponseCallback() {
            @Override
            public void onResponse(String response) {
                // 在这里处理响应数据
                Gson gson = new Gson();
                Type type = new TypeToken<BondsListResponse>(){}.getType();
                BondsListResponse bondsListResponse = gson.fromJson(response, type);
                if (bondsListResponse != null) {
                    // 在这里处理解析后的数据
                    List<BondsListResponse.Data.Bonds> bondsList = bondsListResponse.getData().getBondsList();
                    bondsListLiveData.postValue(bondsList);
                }
            }

            @Override
            public void onPermissionError(String msg) {
                Log.d(TAG, "onPermissionError: " + msg);
            }

            @Override
            public void onInternalError(String msg) {
                Log.d(TAG, "onInternalError: " + msg);
            }

            @Override
            public void onFailure(IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
        });
    }
}
